#!/bin/bash
# PacketCaptureService 启动脚本

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_FILE="${SCRIPT_DIR}/etc/Capture.conf"
LOG_FILE="${SCRIPT_DIR}/log/capture.log"
PYTHON_SCRIPT="${SCRIPT_DIR}/PacketCaptureService.py"

# 检查配置文件是否存在
if [ ! -f "$CONFIG_FILE" ]; then
    echo "错误: 配置文件 $CONFIG_FILE 不存在"
    exit 1
fi

# 检查Python脚本是否存在
if [ ! -f "$PYTHON_SCRIPT" ]; then
    echo "错误: Python脚本 $PYTHON_SCRIPT 不存在"
    exit 1
fi

# 检查Python是否安装
if ! command -v python3 &> /dev/null; then
    echo "错误: 未找到 python3，请先安装 Python 3"
    exit 1
fi

# 函数：检查服务是否已经在运行
check_running() {
    if pgrep -f "PacketCaptureService.py" > /dev/null; then
        echo "服务已经在运行中"
        return 0
    else
        return 1
    fi
}

# 函数：启动服务
start_service() {
    if check_running; then
        exit 1
    fi
    
    echo "启动 PacketCaptureService..."
    echo "配置文件: $CONFIG_FILE"
    echo "日志文件: $LOG_FILE"
    echo "启动时间: $(date)"
    
    # 启动服务
    cd "$SCRIPT_DIR"
    python3 "./PacketCaptureService.py" -c "./etc/Capture.conf"
    
    if [ $? -eq 0 ]; then
        echo "服务正常退出"
    else
        echo "服务异常退出，退出码: $?"
    fi
}

# 函数：停止服务
stop_service() {
    if ! check_running; then
        echo "服务未在运行"
        return
    fi
    
    echo "停止 PacketCaptureService..."
    pkill -f "PacketCaptureService.py"
    
    # 等待进程结束
    sleep 2
    
    if check_running; then
        echo "强制停止服务..."
        pkill -9 -f "PacketCaptureService.py"
    fi
    
    echo "服务已停止"
}

# 函数：查看服务状态
status_service() {
    if check_running; then
        echo "PacketCaptureService 正在运行"
        ps -ef | grep "PacketCaptureService.py" | grep -v grep
    else
        echo "PacketCaptureService 未在运行"
    fi
}

# 函数：查看日志
tail_log() {
    if [ ! -f "$LOG_FILE" ]; then
        echo "日志文件不存在: $LOG_FILE"
        return 1
    fi
    
    echo "正在显示日志文件: $LOG_FILE"
    echo "按 Ctrl+C 退出日志查看"
    tail -f "$LOG_FILE"
}

# 函数：显示帮助信息
show_help() {
    echo "PacketCaptureService 管理脚本"
    echo ""
    echo "使用方法: $0 {start|stop|restart|status|log|help}"
    echo ""
    echo "命令:"
    echo "  start   启动服务"
    echo "  stop    停止服务"
    echo "  restart 重启服务"
    echo "  status  查看服务状态"
    echo "  log     实时查看日志"
    echo "  help    显示此帮助信息"
    echo ""
    echo "配置文件: $CONFIG_FILE"
    echo "日志文件: $LOG_FILE"
}

# 主逻辑
case "$1" in
    start)
        start_service
        ;;
    stop)
        stop_service
        ;;
    restart)
        stop_service
        sleep 2
        start_service
        ;;
    status)
        status_service
        ;;
    log)
        tail_log
        ;;
    help|--help|-h)
        show_help
        ;;
    *)
        # 如果没有参数，默认启动服务
        if [ $# -eq 0 ]; then
            start_service
        else
            echo "错误: 未知命令 '$1'"
            echo "使用 '$0 help' 查看可用命令"
            exit 1
        fi
        ;;
esac